package com.oocl.scp_ssh.scp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import com.oocl.scp_ssh.analyze.CommandAnalzyer;
import com.oocl.scp_ssh.pojo.Command;
import com.oocl.scp_ssh.pojo.impl.LsCommand;
import com.oocl.scp_ssh.pojo.impl.RmCommand;
import com.oocl.scp_ssh.pojo.impl.ScpMsg;

public class ScpClient {

	public static void main(String[] args) throws UnknownHostException,
			IOException {
		String input;
		Scanner scan = new Scanner(System.in);
		ScpJudge judge = new ScpJudge();
		Socket socket = null;

		System.out.println("Please input scp command :");
		input = scan.nextLine();

		// //根据输入的命令，再去生成对应的socket，进行连接，并请求。
		Command cmd = new CommandAnalzyer().analyzeCmd(input);
		if (cmd instanceof LsCommand | cmd instanceof RmCommand) {
			// /LS + RM

			socket = new Socket("127.0.0.1", 8001);

		} else if (cmd instanceof ScpMsg) {
			// //SCP
			ScpMsg scpMsg = judge.judge(input);
			if (scpMsg == null) {
				System.out.println("输入scp命令有误！");
				return;
			}
			File file = new File(scpMsg.getLocalFilePath());
			if (!file.exists()) {
				System.out.println("本地文件 " + file.getAbsolutePath() + " 不存在");
				return;
			}

			socket = new Socket(scpMsg.getRemoteIp(), 8001);
			InputStream in = socket.getInputStream();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			OutputStream out = socket.getOutputStream();

			out.write((input + "\n").getBytes());

			String reply = reader.readLine();
			if (!reply.equals("200ok")) {
				System.out.println(reply);
				return;
			}
			System.out.println("服务器传来： "+ reply);

			// //告诉server 文件大小
			out.write(("fileSize:" + file.length() + "\n").getBytes());

			reply = reader.readLine();
			if (!reply.equals("200ok")) {
				System.out.println(reply);
				return;
			}

			System.out.println("服务器传来： "+ reply);	

			System.out.println("开始上传文件" + file.getAbsolutePath() + "......");

			InputStream fin = new FileInputStream(file);

			int len = 0;
			byte[] buf = new byte[1024];
			while ((len = fin.read(buf)) != -1) {
				out.write(buf, 0, len);
			}

			String uploadRes = reader.readLine();
			System.out.println(uploadRes);
			
			fin.close();
			// String uploadRes = reader.readLine();
			// System.out.println(uploadRes);
			//
			// ///关闭
			// out.write(("Close\n").getBytes());
			//
			System.out.println("成功上传文件！");
			out.close();
			reader.close();
			socket.close();

		}

	}

}
